package cn.wolfcode.luowowo.member.service.impl;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AssertUtil;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.mapper.UserInfoMapper;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.member.vo.UserCommentVO;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;

@Service
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String Sender;


    @Override
    public boolean checkPhone(String phone) {
        int count = userInfoMapper.selectCountByPhone(phone);
        return count > 0;
    }

    @Override
    public void sendVerifyCode(String phone) {
        //1.拼接验证码
        String code = UUID.randomUUID().toString().substring(0, 4);

        //2.缓存短信
        userInfoRedisService.sendVerifyCode(phone, code);

        //3.发送短信
        StringBuilder sb = new StringBuilder();
        sb.append("您的手机验证码是: ").append(code).append(" ,请在5分钟内使用!");
        System.out.println(sb);

    }

    @Override
    public void userRegist(String phone, String nickname, String password, String rpassword, String verifyCode) throws LogicException {
        //判断传进来的值,前端页面判断实际上相当于没有判断
        AssertUtil.hasLength(phone, "手机号码不能为空!");
        AssertUtil.hasLength(nickname, "昵称不能为空!");
        AssertUtil.hasLength(password, "密码不能为空!");
        AssertUtil.hasLength(rpassword, "密码确认不能为空!");
        AssertUtil.hasLength(verifyCode, "验证码不能为空!");

        //判断密码和确认密码是否相等
        AssertUtil.isEquals(password, rpassword, "两次输入的密码必须一致");

        //判断手机号码格式是否正确
        if (!Pattern.matches("^[1]([3][0-9]{1}|59|58|88|89)[0-9]{8}$", phone)) {
            throw new RuntimeException("手机号格式不正确");
        }

        //判断验证码是否一致
        String code = userInfoRedisService.getVerifyCode(phone);
        //System.out.println(code);
        AssertUtil.hasLength(code, "验证码不存在或者验证码已过期");

        //忽略大小写
        AssertUtil.isEquals(code.toLowerCase(), verifyCode.toLowerCase(), "验证码错误");

        //注册
        UserInfo userInfo = new UserInfo();
        userInfo.setPhone(phone);
        userInfo.setPassword(password);
        userInfo.setNickname(nickname);
        userInfo.setState(UserInfo.STATE_NORMAL);//状态值 正常
        userInfo.setHeadImgUrl("/images/meituan.jpg");
        userInfo.setLevel(1);
        userInfoMapper.insert(userInfo);
    }

    @Override
    public String userLogin(String username, String password) throws LogicException {
        //判断传进来的值是否为空
        AssertUtil.hasLength(username, "用户名不能为空!");
        AssertUtil.hasLength(password, "密码不能为空!");
        //查询是否有该用户
        UserInfo userInfo = userInfoMapper.selectByUsernameAndPassword(username, password);
        //判断是否为空,为空的话表示没有该用户
        if (userInfo == null) {
            throw new LogicException("用户名或密码错误");
        }
        //创建一个令牌
        String token = UUID.randomUUID().toString().replaceAll("-","");

        //将token缓存进redis
        userInfoRedisService.sendToken(token,userInfo);


        return token;
    }

    @Override
    public List<UserInfo> list() {
        return userInfoMapper.selectAll();
    }

    public void updateUserInfo(UserInfo userInfo) {
        userInfoMapper.updateUserInfo(userInfo);
    }

    public UserInfo get(Long id) {
        return userInfoMapper.selectByPrimaryKey(id);
    }

    public void userUpdatePassword(String phone, String password, String rpassword, String verifyCode)throws LogicException {
        //判断传进来的值,前端页面判断实际上相当于没有判断
        AssertUtil.hasLength(password, "密码不能为空!");
        AssertUtil.hasLength(rpassword, "密码确认不能为空!");
        AssertUtil.hasLength(verifyCode, "验证码不能为空!");

        //判断密码和确认密码是否相等
        AssertUtil.isEquals(password, rpassword, "两次输入的密码必须一致");

        //判断验证码是否一致
        String code = userInfoRedisService.getVerifyCode(phone);
        //System.out.println(code);
        AssertUtil.hasLength(code, "验证码不存在或者验证码已过期");

        //忽略大小写
        AssertUtil.isEquals(code.toLowerCase(), verifyCode.toLowerCase(), "验证码错误");

        //更改密码
        UserInfo userInfo = userInfoMapper.selectUserByPhone(phone);
        userInfo.setPassword(password);
        userInfoMapper.updatePassword(userInfo.getId(),password);
    }

    public void sendVerifyCodeToEmail(String email) {
        //1.拼接验证码
        String code = UUID.randomUUID().toString().substring(0, 4);

        //2.缓存邮箱验证码
        userInfoRedisService.sendVerifyCodeToEmail(email, code);

        //3.发送邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(Sender);
        message.setTo(email);
        message.setSubject("主题：简单邮件");
        message.setText("尊敬的用户您好,您本次注册的验证码是:" + code);
        mailSender.send(message);
    }

    public void userUpdatePasswordByEmail(String email, String password, String rpassword, String verifyCode) {
        //判断传进来的值,前端页面判断实际上相当于没有判断
        AssertUtil.hasLength(password, "密码不能为空!");
        AssertUtil.hasLength(rpassword, "密码确认不能为空!");
        AssertUtil.hasLength(verifyCode, "验证码不能为空!");

        //判断密码和确认密码是否相等
        AssertUtil.isEquals(password, rpassword, "两次输入的密码必须一致");

        //判断验证码是否一致
        String code = userInfoRedisService.getVerifyCode(email);
        //System.out.println(code);
        AssertUtil.hasLength(code, "验证码不存在或者验证码已过期");

        //忽略大小写
        AssertUtil.isEquals(code.toLowerCase(), verifyCode.toLowerCase(), "验证码错误");

        //更改密码
        UserInfo userInfo = userInfoMapper.selectUserByEmail(email);
        userInfo.setPassword(password);
        userInfoMapper.updatePassword(userInfo.getId(),password);
        //后台打印验证码调试
        StringBuilder sb = new StringBuilder();
        sb.append("您的邮箱验证码是: ").append(code).append(" ,请在5分钟内使用!");
        System.out.println(sb);
    }

    public boolean checkEmail(String email,Long id) {
        int count = userInfoMapper.selectCountByEmail(email);
        if (!(count>0)){
            userInfoMapper.updateTemporaryEmailById(email,id);
        }
        return count > 0;
    }

    public void userUpdateEmailByTemporaryEmail(String temporaryEmail, String verifyCode) {
        //判断传进来的值,前端页面判断实际上相当于没有判断
        AssertUtil.hasLength(verifyCode, "验证码不能为空!");

        //判断验证码是否一致
        String code = userInfoRedisService.getVerifyCode(temporaryEmail);
        //System.out.println(code);
        AssertUtil.hasLength(code, "验证码不存在或者验证码已过期");

        //忽略大小写
        AssertUtil.isEquals(code.toLowerCase(), verifyCode.toLowerCase(), "验证码错误");

        //更改邮箱
        UserInfo userInfo = userInfoMapper.selectUserByTemporaryEmail(temporaryEmail);
        userInfoMapper.updateEmail(userInfo.getId(),temporaryEmail);
        //后台打印验证码调试
        StringBuilder sb = new StringBuilder();
        sb.append("您的邮箱验证码是: ").append(code).append(" ,请在5分钟内使用!");
        System.out.println(sb);
    }

    public void sendVerifyCodeToTemporaryEmail(String temporaryEmail) {
        //1.拼接验证码
        String code = UUID.randomUUID().toString().substring(0, 4);

        //2.缓存邮箱验证码
        userInfoRedisService.sendVerifyCodeToEmail(temporaryEmail, code);

        //3.发送邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(Sender);
        message.setTo(temporaryEmail);
        message.setSubject("主题：简单邮件");
        message.setText("尊敬的用户您好,您本次修改邮箱的验证码是:" + code);
        mailSender.send(message);
    }

    public boolean checkNewPhone(String phone, Long id) {
        int count = userInfoMapper.selectCountByPhone(phone);
        if (!(count>0)){
            userInfoMapper.updateTemporaryPhoneById(phone,id);
        }
        return count > 0;
    }

    public void userUpdatePhoneByTemporaryPhone(String temporaryPhone, String verifyCode) {
        //判断传进来的值,前端页面判断实际上相当于没有判断
        AssertUtil.hasLength(verifyCode, "验证码不能为空!");

        //判断手机号码格式是否正确
        if (!Pattern.matches("^[1]([3][0-9]{1}|59|58|88|89)[0-9]{8}$", temporaryPhone)) {
            throw new RuntimeException("手机号格式不正确");
        }

        //判断验证码是否一致
        String code = userInfoRedisService.getVerifyCode(temporaryPhone);
        //System.out.println(code);
        AssertUtil.hasLength(code, "验证码不存在或者验证码已过期");

        //忽略大小写
        AssertUtil.isEquals(code.toLowerCase(), verifyCode.toLowerCase(), "验证码错误");

        //更改手机
        UserInfo userInfo = userInfoMapper.selectUserByTemporaryPhone(temporaryPhone);
        userInfoMapper.updatePhone(userInfo.getId(),temporaryPhone);
        //后台打印验证码调试
        StringBuilder sb = new StringBuilder();
        sb.append("您的邮箱验证码是: ").append(code).append(" ,请在5分钟内使用!");
        System.out.println(sb);
    }

    @Override
    public List<UserInfo> queryByUserIdForFollow(Long id) {
        List<UserInfo> list = new ArrayList<>();
        String follows = userInfoMapper.queryByUserIdForFollow(id);
        if (follows !=null) {
            String[] stringArr = follows.split(",");
            for (int i = 0; i < stringArr.length; i++) {
                UserInfo userInfo = userInfoMapper.selectByPrimaryKey(Long.valueOf(stringArr[i]));
                list.add(userInfo);
            }
        }
        return list;
    }



    @Override
    public UserInfo getUserByid(Long uid) {
        return userInfoMapper.selectByUid(uid);
    }

    @Override
    public List<UserInfo> listUser() {
        return userInfoMapper.selectByUser();
    }

    @Override
    public void updateStatisByVo(UserCommentVO vo1) {
        userInfoMapper.updateStatisByVo(vo1);
    }
}
